###
 # @Author: didiplus
 # @Date: 2024-09-07 11:16:11
 # @LastEditTime: 2024-09-07 11:52:29
 # @LastEditors: didiplus
 # @Description: 
 # @FilePath: \pythonscript\shell\scp_test.sh
###
#!/bin/bash

if ! command -v pidstat &>/dev/null || !command -v bc &>/dev/null; 
then
    echo "请安装 sysstat 和 bc 软件包"
    exit 1
fi

#rsync -avz demo.file  root@192.168.1.200:/tmp &
scp ./demo.file root@192.168.1.200:/tmp &
SCP_PID=$!

CPU_USAGE_SUM=0
COUNT=0

while kill -0 $SCP_PID 2> /dev/null; do
#从pidstat 中正确捕获CPU的值
    CPU_USAGE=$(pidstat -p $SCP_PID 1 1 | awk '/[0-9]:[0-9][0-9]:[0-9][0-9] PM|AM/ && /(scp|rsync)/ {print $9}')
    if [[ $CPU_USAGE =~^[0-9]+([.][0-9]+)?$ ]]; then
        CPU_USAGE_SUM=$(echo "$CPU_USAGE_SUM + $CPU_USAGE" | bc)
        COUNT=$((COUNT + 1))
    fi
    sleep 1
done
if [ $COUNT -ne 0 ]; then
    AVG_CPU=$(echo "scale=2; $CPU_USAGE_SUM / $COUNT" | bc)
    echo "平均 CPU : $AVG_CPU%"
else
    echo "没有采集到 CPU 数据."

fi